package com.fly.web.controller;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.concurrent.Callable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;

import com.fly.core.entity.JsonResult;

import io.netty.channel.ConnectTimeoutException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

@Slf4j
@Api(tags = "文件测试接口")
@RestController
@RequestMapping("//server/backUpload")
public class TestController
{
    @Autowired
    RestTemplate restTemplate;
    
    @Autowired
    WebClient webClient;
    
    @ApiOperation("后台上传1")
    @GetMapping("/restTemplate")
    public Callable<JsonResult<String>> backDownUpload()
    {
        return () -> {
            // 字节流转发到上传接口
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
            MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
            Resource resource = new FileSystemResource("E:\\soft\\CentOS-7-x86_64-DVD-2009.iso");
            params.add("file", resource);
            params.add("id", "1");
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);
            String uploadUrl = "http://124.71.129.204:8083/post";
            restTemplate.postForEntity(uploadUrl, requestEntity, String.class);
            return JsonResult.success("success");
        };
    }
    
    @ApiOperation("后台上传2")
    @GetMapping("/webClient")
    public JsonResult<String> backDownUploadByWebclient()
    {
        Mono<String> mono = webClient.post()
            .uri("http://124.71.129.204:8083/post")
            .contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .acceptCharset(StandardCharsets.UTF_8)
            .accept(MediaType.APPLICATION_JSON, MediaType.TEXT_HTML)
            .body(BodyInserters.fromMultipartData("q1", "java").with("q2", "python").with("file", new FileSystemResource("E:\\soft\\CentOS-7-x86_64-DVD-2009.iso")))
            .retrieve() // 获取响应体
            .onStatus(HttpStatus::isError, clientResponse -> {
                return Mono.error(new Exception(clientResponse.statusCode().value() + " error code"));
            })
            .bodyToMono(String.class)// 响应数据类型转换
            .doOnError(ConnectTimeoutException.class, err -> {
                log.error("发生错误：", err.getMessage());
            });
        mono.subscribe(body -> log.info("----- response: {}", body));
        return JsonResult.success("success");
    }
}
